package com.example.springboot.controller;

import com.example.springboot.common.Result;
import com.example.springboot.controller.request.AdminPageRequest;
import com.example.springboot.controller.request.LoginRequest;
import com.example.springboot.dto.AdminLoginDTO;
import com.example.springboot.entity.Admin;
import com.example.springboot.service.AdminService;
import com.example.springboot.utils.TimerTask.TaskInfo;
import com.example.springboot.utils.TimerTask.TaskType;
import com.example.springboot.utils.TimerTask.TimerTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * ClassName:AdminController
 * Package:com.example.springboot.controller
 * Description:
 *
 * @Author: Gao
 * @Create: 2023/2/2 - 11:12
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    AdminService adminService;
    @Resource
    TimerTask timerTask;

    @GetMapping("/")
    public Result list() {
        List<Admin> users = adminService.list();
        return Result.success(users);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") int id) {
        Admin admin = adminService.getById(id);
        return Result.success(admin);
    }
/*该接口进行测试token校验*/
    @GetMapping("/page")
    public Result page(AdminPageRequest pageRequest) {
        boolean taskIsEnd = timerTask.taskIsEnd(pageRequest.getAccount());
        if (taskIsEnd)
            return Result.error("token过期，拒绝访问");
        Object page = adminService.pageInfo(pageRequest);
        return Result.success(page);
    }

    @PutMapping("/")
    public Result update(@RequestBody Admin admin) {
        adminService.update(admin);
        return Result.success();
    }

    @PostMapping("/")
    public Result save(@RequestBody Admin admin) {
        adminService.save(admin);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable int id) {
        adminService.deleteById(id);
        return Result.success();
    }
/*该接口访问生成token*/
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest request) {
        AdminLoginDTO loginDTO = adminService.login(request);
        /*生成token时间为3秒*/
        timerTask.setTimer(loginDTO.getAccount(),new TaskInfo(loginDTO.getAccount(),3000, TaskType.TASK_DELETE_CACHE));
        return Result.success(loginDTO);
    }

}

